package com.cats.bi.sqltool.function;

import com.cats.bi.sqltool.basic.AbstractSearchable;
import com.cats.bi.sqltool.basic.Column;
import org.apache.commons.lang3.StringUtils;

/**
 * @author duxiaobo
 * @date 2021/9/24:24 下午
 */
public class Rank extends Column {
    private String partition;
    private String sort;

    public Rank(String name) {
        super(name);
    }

    public Rank(String table, String name) {
        super(table, name);
    }

    public Rank(AbstractSearchable table, String tableAlias, String name) {
        super(table, tableAlias, name);
    }

    public Rank(AbstractSearchable table, String tableAlias, String name, String partition) {
        super(table, tableAlias, name);
        this.partition = partition;
    }

    public Rank(AbstractSearchable table, String tableAlias, String name, String partition, String sort) {
        super(table, tableAlias, name);
        this.partition = partition;
        this.sort = sort;
    }

    @Override
    public void toSql(StringBuilder sb) {
        sb.append("RANK() OVER(");
        if (!StringUtils.isBlank(partition)) {
            sb.append(" PARTITION BY ")
                    .append(partition);
        }
        sb.append(" ORDER BY ");
        super.toSql(sb);
        if (!StringUtils.isBlank(sort)) {
            sb.append(" ").append(sort);
        }
        sb.append(")");
    }
}
